package cn.kgc.dao.impl;

import cn.kgc.dao.UserDao;
import cn.kgc.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/6/27
 * @description
 */
public class UserDaoImpl implements UserDao {

    private static SqlSessionFactory factory;

    static {
        // 创建SqlSessionFactoryBuilder  来生成   SqlSessionFactory
        // 加载全局配置文件
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    }

    @Override
    public List<User> userList(String statement) {

        SqlSession sqlSession = factory.openSession();
        List<User> usrs = sqlSession.selectList(statement);

        sqlSession.close();
        return usrs;
    }

    @Override
    public User selectOne(String statement,Integer id) {
        SqlSession sqlSession = factory.openSession();
        //  查询一个用户信息
        User u = sqlSession.selectOne(statement, id);
        sqlSession.close();
        return u;
    }

    @Override
    public Integer addUser(String statement,User user) {
        SqlSession sqlSession = factory.openSession();
        int insert = sqlSession.insert(statement, user);

        // 添加数据  默认不会自动提交事务  数据不会持久化    手动提交事务
        sqlSession.commit();
        sqlSession.close();
        return  insert;
    }

    @Override
    public Integer updateUser(String statement,User user) {
        SqlSession sqlSession = factory.openSession(true);
        int update = sqlSession.update(statement, user);
        sqlSession.close();
        return update;
    }

    @Override
    public Integer deleteUser(String statement,Integer id) {
        SqlSession sqlSession = factory.openSession(true);
        int delete = sqlSession.delete(statement, id);
        sqlSession.close();
        return  delete;
    }
}
